import Stomp from 'stompjs'; // 需确保已安装 stompjs 库

export default class WebSocketClient {
  /**
   * 构造函数
   * @param {Object} config 配置对象
   * @param {string} config.websocketUrl WebSocket 服务器地址
   * @param {Function} [config.topicBuilder] 动态生成订阅主题的函数（需返回字符串）
   * @param {Function} [config.onMessage] 接收到消息时的回调
   * @param {Function} [config.onConnect] 连接成功时的回调
   * @param {Function} [config.onError] 连接失败时的回调
   * @param {Object} [config.headers] 连接头信息（如认证信息）
   */
  constructor(config) {
    this.config = {
      websocketUrl: config.websocketUrl,
      topicBuilder: config.topicBuilder || ((userId) => `/topic/user.${userId}`),
      onMessage: config.onMessage || (() => {}),
      onConnect: config.onConnect || (() => {}),
      onError: config.onError || ((error) => console.error('WebSocket Error:', error)),
      headers: config.headers || {},
    };
    this.stompClient = null;
  }

  /**
   * 连接 WebSocket
   * @param {string} userId 用户标识（用于动态构建订阅主题）
   */
  connect(userId) {
    const socket = new WebSocket(this.config.websocketUrl);
    this.stompClient = Stomp.over(socket);
    this.stompClient.debug = null; // 禁用调试日志

    this.stompClient.connect(
      this.config.headers,
      (frame) => {
        const topic = this.config.topicBuilder(userId);
        this.stompClient.subscribe(topic, (message) => {
          this.config.onMessage(JSON.parse(message.body));
        });
        this.config.onConnect(frame);
      },
      (error) => this.config.onError(error)
    );
  }

  /** 断开 WebSocket 连接 */
  disconnect() {
    if (this.stompClient && this.stompClient.connected) {
      this.stompClient.disconnect();
    }
  }
}
